package com.example.account.controller;

import com.example.account.domain.User;

import com.example.account.repository.UserRepository;

import com.example.account.service.UserService;
import com.example.account.util.*;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import net.sf.json.JSONObject;

import java.text.ParseException;

import java.util.ArrayList;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/enter")
    public Object login(@RequestParam("code") String code
    ) throws Exception {
        User user = new User();
        List<Map> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        String appid = "wxe1f56d5759c975cd";
        String secret = "1ded3d496865c184f20b5bf35aa59d7b";
        JSONObject jsonObject = getUserWXLoginInfo(code, appid, secret);
        String openid = (String) jsonObject.get("openid");
        String sessionKey = (String) jsonObject.get("session_key");

        boolean p1 = false;
        if (openid != null && !"".equals(openid)) {
            for (User u : userRepository.findAll()) {
                if (openid.equals(u.getOpenid())) {
                    map.put("code", "1");
                    map.put("tel", u.getTel());
                    map.put("nickName", u.getNickname());
                    map.put("avatarUrl", u.getAvatarUrl());
                    map.put("gender", u.getGender());//性别
                    map.put("msg", "用户已注册 请登录！");
                    p1 = true;
                    return map;
                }
                p1 = false;
            }
            if (!p1) {
                map.put("code", "2");
                map.put("msg", "该用户未注册 快去注册吧！");
                return map;
            }
        } else {
            map.put("code", "2");
            map.put("msg", "该用户未注册 快去注册吧！");
            return map;
        }
        return map;
    }


    @RequestMapping(value = "/login")
    public Object login(@RequestParam("tel") String tel,
                        @RequestParam("pwd") String pwd,
                        @RequestParam("code") String code

    ) throws Exception {
        User user = new User();
        List<Map> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        String appid = "wxe1f56d5759c975cd";
        String secret = "1ded3d496865c184f20b5bf35aa59d7b";
        JSONObject jsonObject = getUserWXLoginInfo(code, appid, secret);
        String openid = (String) jsonObject.get("openid");
        String sessionKey = (String) jsonObject.get("session_key");
        boolean pd1 = false;
        boolean pd2 = false;
        boolean pd3 = false;

        for (User u : userRepository.findAll()) {
            if (openid.equals(u.getOpenid())) {
                if (openid.equals(u.getOpenid()) && tel.equals(u.getTel())) {
                    if (pwd.equals(u.getPwd())) {

                        map.put("tel", u.getTel());
                        map.put("pwd", u.getPwd());
                        map.put("nickName", u.getNickname());
                        map.put("avatarUrl", u.getAvatarUrl());
                        map.put("gender", u.getGender());
                        map.put("code", "11");
//                        list.add(map);
                        pd2 = true;
                    }
                    pd1 = true;
                }
                pd3 = true;
            }


        }
        if (!pd1) {
            map.put("code", "66");
            map.put("msg", "你填写的手机号不是该微信号注册的手机号码！重新填写！");
            return map;
        }
        if (!pd2) {
            map.put("code", "99");
            map.put("msg", "密码输入错误！");
            return map;
        }
        if (!pd3) {
            map.put("code", "22");
            map.put("msg", "你填写的手机号不是该微信号注册的手机号码！重新填写");
            return map;
        }

        return map;
    }




    @PostMapping(value = "/register1")
    public Map<String, Object> login(@RequestParam("nickName") String nickName,
                                     @RequestParam("avatarUrl") String avatarUrl,
                                     @RequestParam("gender") Integer gender,
                                     @RequestParam("code") String code,
                                     @RequestParam("tel") String tel,
                                     @RequestParam("pwd") String pwd) throws Exception {
        //请求微信api获取用户的openid和sessionKey
        Map<String, Object> map = new HashMap<>();
        String appid = "wxe1f56d5759c975cd";
        String secret = "1ded3d496865c184f20b5bf35aa59d7b";
        JSONObject jsonObject = getUserWXLoginInfo(code, appid, secret);
        String openid = (String) jsonObject.get("openid");
        String sessionKey = (String) jsonObject.get("session_key");
        //通过openid查询数据库是否有此用户
        if (openid != null && !"".equals(openid)) {
            for (User u : userRepository.findAll()) {
                if ((openid.equals(u.getOpenid())) || (tel.equals(u.getTel()))) {
                    map.put("code", "99");
                    map.put("msg", "该微信号已有授权账号，请勿重复！");
                    return map;
                }
                if ((tel.equals(u.getTel()))) {
                    map.put("code", "66");
                    map.put("msg", "该手机号已有授权账号，请勿重复！");
                    return map;
                }
            }
            User users = new User();
            users.setTel(tel);
            users.setPwd(pwd);
            users.setOpenid(openid);
            users.setAvatarUrl(avatarUrl);
            users.setNickname(nickName);
            users.setGender(gender);
            userRepository.save(users);
            map.put("code", "00");
            map.put("msg", "注册授权成功！");
            map.put("users", users);
            return map;
        } else {
            map.put("code", "99");
            map.put("msg", "授权失败！");
            return map;
        }
    }


    private JSONObject getUserWXLoginInfo(String wxCode, String AppID, String AppSecret) throws ParseException {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        Map<String, String> requestUrlParam = new HashMap<String, String>();
        requestUrlParam.put("appid", AppID);    //开发者设置中的appId
        requestUrlParam.put("secret", AppSecret);    //开发者设置中的appSecret
        requestUrlParam.put("js_code", wxCode);    //小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");    //默认参数
        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        JSONObject jsonObject = JSONObject.fromObject(UrlUtil.sendPost(requestUrl, requestUrlParam));
        return jsonObject;
    }


}
